package org.venus.onvif.controller;

import com.google.gson.Gson;
import de.onvif.soap.OnvifDevice;
import de.onvif.soap.devices.PtzDevices;
import org.onvif.ver10.schema.Profile;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.venus.onvif.config.Config;
import org.venus.onvif.entity.OnvifHelp;
import org.venus.onvif.entity.Video;
import org.venus.onvif.http.AjaxResult;
import org.venus.onvif.util.InitUtil;

import javax.xml.soap.SOAPException;
import java.net.ConnectException;
import java.util.HashMap;
import java.util.List;


/**
 * @author zhuhui
 * @date 2023/5/5 14:50
 */
@RestController
@RequestMapping("monitor")
@CrossOrigin
public class MonitorController {

    private float ptzStep = Config.getPtzStep();
    private float zoomStep = 1;


    private HashMap<String, OnvifHelp> onvifDeviceHashMap = new HashMap<>();

    public Video getCameraList(String id) {
        /*String content = readFile(fileLocation);
        System.out.println(content);
        List<Video> videoList =
                JSON.parseObject(content, new TypeReference<List<Video>>() {
                });*/
        Video video = null;
        if (Config.videos != null) {
            video = Config.videos.stream().filter(item -> item.id.equals(id)).findFirst().get();
        }
        return video;
    }


    @GetMapping(value = "/up")
    public AjaxResult up(String id) {
        //mointor(0f, 0.2f, 0f, id);
        ptz(0f, ptzStep, 0f, id);
        System.out.println("云台上:" + new Gson().toJson(getCameraList(id)));
        return AjaxResult.success();
    }

    @GetMapping(value = "/down")
    public AjaxResult down(String id) {
        ptz(0f, -ptzStep, 0f, id);
        System.out.println("云台下:" + new Gson().toJson(getCameraList(id)));
        return AjaxResult.success();
    }

    @GetMapping(value = "/left")
    public AjaxResult left(String id) {
        ptz(-ptzStep, 0f, 0f, id);
        System.out.println("云台左:" + new Gson().toJson(getCameraList(id)));
        return AjaxResult.success();
    }

    @GetMapping(value = "/right")
    public AjaxResult right(String id) {
        ptz(ptzStep, 0f, 0f, id);
        System.out.println("云台右:" + new Gson().toJson(getCameraList(id)));
        return AjaxResult.success();
    }

    @GetMapping(value = "/big")
    public AjaxResult big(String id) {
        //mointor2(0f, 0f, ZOOM_STEP, id);
        zoom(0f, 0f, zoomStep, id);
        System.out.println("变倍加:" + new Gson().toJson(getCameraList(id)));
//        stopMove(id);
        return AjaxResult.success();
    }

    @GetMapping(value = "/small")
    public AjaxResult small(String id) {
        zoom(0f, 0f, -zoomStep, id);
        System.out.println("变倍减:" + new Gson().toJson(getCameraList(id)));
//        stopMove(id);
        return AjaxResult.success();
    }

    @GetMapping(value = "/stopMove")
    public AjaxResult stopMove(String id) {
        /*try {
            OnvifHelp onvifHelps = onvifDeviceHashMap.get(id);
            onvifHelps.ptzDevices.stopMove(onvifHelps.profileToken);
        } catch (Exception e) {
            e.printStackTrace();
        }*/
        if (id == null) {
            return AjaxResult.success();
        }
        System.out.println("云台停:" + new Gson().toJson(getCameraList(id)));
        OnvifHelp onvifHelp = InitUtil.getOnvif(id);
        if (onvifHelp == null) {
            System.out.println("设备:" + id + "-->onvif控制对象获取失败,请确认设备是否支持onvif云台控制,如果不支持可以忽略此错误");
            return AjaxResult.success();
        }
        onvifHelp.ptzDevices.stopMove(onvifHelp.profileToken);
        return AjaxResult.success();
    }

    void mointor(float x, float y, float z, String id) {
        try {
            OnvifHelp onvifHelps = onvifDeviceHashMap.get(id);

            OnvifDevice nvt = null;
            String profileToken = "";
            PtzDevices ptzDevices = null;
            if (onvifHelps == null) {
                Video video = getCameraList(id);
                System.out.println("------------------" + video.ip + "------------------");
                System.out.println("没有缓存的情况");
                nvt = new OnvifDevice(video.ip, video.userName, video.password);
                OnvifHelp onvifHelp = new OnvifHelp();
                onvifHelp.onvifDevice = nvt;

                List<Profile> profiles = nvt.getDevices().getProfiles();
                // PROFILE_000
                // 获取视频参数
                String videoSourceToken = profiles.get(0).getVideoSourceConfiguration().getSourceToken();
                System.err.println("videoSourceToken=====" + videoSourceToken);
                // 设置视频参数上下转动
                profileToken = profiles.get(0).getToken();


                ptzDevices = nvt.getPtz();

                onvifHelp.profileToken = profileToken;
                onvifHelp.ptzDevices = ptzDevices;
                onvifDeviceHashMap.put(id, onvifHelp);
            } else {
                nvt = onvifHelps.onvifDevice;
                profileToken = onvifHelps.profileToken;
                ptzDevices = onvifHelps.ptzDevices;
            }


//            PTZStatus status = ptzDevices.getStatus(profileToken);
            // 获取当前焦距
//            PTZVector position = status.getPosition();
//            float zoom = 0f;
//            if (position != null && position.getZoom() != null) {
//                zoom = position.getZoom().getX();
//                System.out.println("当前焦距：" + zoom);
//            }
//            zoom = zoom + z;
//            if (zoom > 1) {
//                zoom = 1;
//            }
//            if (zoom < 0) {
//                zoom = 0;
//            }

            ptzDevices.continuousMove(profileToken, x, y, 0f);
            // System.err.println(nvt.getPtz().getPresets(profileToken));
            //-1：表示云台的水平位置（即左右方向）的相对移动量，这里的值为-1表示向左移动。如果您想向右移动，则将该值更改为正数。
            //1：表示云台的垂直位置（即上下方向）的相对移动量，这里的值为1表示向上移动。如果您想向下移动，则将该值更改为负数。
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void mointor2(float x, float y, float z, String id) {
        try {
            OnvifHelp onvifHelps = onvifDeviceHashMap.get(id);

            OnvifDevice nvt = null;
            String profileToken = "";
            PtzDevices ptzDevices = null;
            if (onvifHelps == null) {
                Video video = getCameraList(id);
                System.out.println("------------------" + video.ip + "------------------");
                System.out.println("没有缓存的情况");
                nvt = new OnvifDevice(video.ip, video.userName, video.password);
                OnvifHelp onvifHelp = new OnvifHelp();
                onvifHelp.onvifDevice = nvt;

                List<Profile> profiles = nvt.getDevices().getProfiles();
                // PROFILE_000
                // 获取视频参数
                String videoSourceToken = profiles.get(0).getVideoSourceConfiguration().getSourceToken();
                System.err.println("videoSourceToken=====" + videoSourceToken);
                // 设置视频参数上下转动
                profileToken = profiles.get(0).getToken();
                ptzDevices = nvt.getPtz();
                onvifHelp.ptzDevices = ptzDevices;

                onvifHelp.profileToken = profileToken;
                onvifDeviceHashMap.put(id, onvifHelp);
            } else {
                nvt = onvifHelps.onvifDevice;
                profileToken = onvifHelps.profileToken;
                ptzDevices = onvifHelps.ptzDevices;
            }


//            PTZStatus status = ptzDevices.getStatus(profileToken);
            // 获取当前焦距
//            PTZVector position = status.getPosition();
//            float zoom = 0f;
//            if (position != null && position.getZoom() != null) {
//                zoom = position.getZoom().getX();
//                System.out.println("当前焦距：" + zoom);
//            }
//            zoom = zoom + z;
//            if (zoom > 1) {
//                zoom = 1;
//            }
//            if (zoom < 0) {
//                zoom = 0;
//            }

            ptzDevices.continuousMove(profileToken, x, y, z);
            // System.err.println(nvt.getPtz().getPresets(profileToken));
            //-1：表示云台的水平位置（即左右方向）的相对移动量，这里的值为-1表示向左移动。如果您想向右移动，则将该值更改为正数。
            //1：表示云台的垂直位置（即上下方向）的相对移动量，这里的值为1表示向上移动。如果您想向下移动，则将该值更改为负数。
        } catch (ConnectException e) {
            System.err.println("Could not connect to NVT.");
        } catch (SOAPException e) {
            e.printStackTrace();
        }
    }

    private void ptz(float x, float y, float z, String id) {
        System.out.println(x + ":" + y + ":" + z);
        if (id == null) {
            return;
        }
        OnvifHelp onvifHelp = InitUtil.getOnvif(id);
        if (onvifHelp == null) {
            System.out.println("设备:" + id + "-->onvif控制对象获取失败,请确认设备是否支持onvif云台控制,如果不支持可以忽略此错误");
            return;
        }
        onvifHelp.ptzDevices.continuousMove(onvifHelp.profileToken, x, y, z);
    }

    private void zoom(float x, float y, float z, String id) {
        if (id == null) {
            return;
        }
        OnvifHelp onvifHelp = InitUtil.getOnvif(id);
        if (onvifHelp == null) {
            System.out.println("设备:" + id + "-->onvif控制对象获取失败,请确认设备是否支持onvif云台控制,如果不支持可以忽略此错误");
            return;
        }
        onvifHelp.ptzDevices.continuousMove(onvifHelp.profileToken, x, y, z);
    }
}
